package com.school.information.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    /**
     * springboot2.x 使用LettuceConnectionFactory 代替 RedisConnectionFactory
     * application.yml配置基本信息后,springboot2.x  RedisAutoConfiguration能够自动装配
     * LettuceConnectionFactory 和 RedisConnectionFactory 及其 RedisTemplate
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericFastJsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericFastJsonRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }


    /**
     * 对redis的value使用以下序列化方式进行序列化操作：
     *
     * 1：JdkSerializationRedisSerializer:
     *
     * 2：GenericJackson2JsonRedisSerializer
     *
     * 3：StringRedisSerializer
     *
     * 4：GenericFastJsonRedisSerializer
     *
     * 发现只有4：GenericFastJsonRedisSerializer，最好用，不报错
     *
     * 下面一个个简单介绍以下
     *
     * 1：JdkSerializationRedisSerializer:
     *
     * 序列化java对象碰到下面的报错：
     *
     *
     * DefaultSerializer requires a Serializable payload but received an object of type [com.everestfortune.cf.bean.CaseInfoBean]
     * 切换到logDB
     *
     * 原因：使用JdkSerializationRedisSerializer序列化的Bean必须实现Serializable接口
     *
     *
     *
     * 2：GenericJackson2JsonRedisSerializer
     *  获取redis中的数据碰到下面的报错：
     * 2019-04-26 11:26:41.510 ERROR 11656 --- [nio-9076-exec-7] c.e.cf.controller.ApplyController
     * : redis获取数据失败，mes=Could not read JSON: Cannot construct instance of `java.time.LocalDate`
     * (no Creators, like default construct, exist):
     *  cannot deserialize from Object value (no delegate- or property-based Creator)
     *
     * 原因：LocalDate这是java8新增的类，GenericJackson2JsonRedisSerializer序列化方式无法识别
     *
     *
     *
     *
     *
     *  3：StringRedisSerializer
     *  不能序列化Bean，只能序列化字符串类型的数据，
     *
     * 如果value都是字符串类型，可以用该方式序列化
     *
     *
     * 4： GenericFastJsonRedisSerializer：
     *
     * 目前没有发现问题，很好用
     */
}
